var request;
var db;
var dbName = "TestDB"; //数据库名称
var dbVersion = 1.0; //数据库版本
var tablename = "Test"; //表名
var TableKey = 'key';//表主键

$(document).ready(function(){
    window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
    if(!window.indexedDB){
        console.log("你的浏览器不支持IndexedDB");
    }else{
        request = window.indexedDB.open("TestDB", dbVersion);
        request.onerror = function(event){
            console.log("数据库打开失败^~^");
        }
        request.onupgradeneeded   = function(event){
            console.log("Upgrading");
            db = event.target.result;
            var objectStore = db.createObjectStore(tablename, { keyPath : TableKey });
        };
        request.onsuccess  = function(event){
            console.log("成功打开数据库^_^");
            db = event.target.result;
        }
    }
});
/**
 * [indexdb_add 添加数据]
 * @param  {[type]} rollNo [主键索引名称]
 * @param  {[type]} name   [存入的数据字符串]
 * @return {[type]}        [返回状态]
 */
function indexdb_add(rollNo,name){
    var transaction = db.transaction([tablename],"readwrite");
transaction.oncomplete = function(event) {
    console.log("数据添加成功^_^");
    $("#result").html("Add : Success");
    return true;
};
transaction.onerror = function(event) {
    console.log("数据添加失败^~^");
};  
    var objectStore = transaction.objectStore(tablename);
    objectStore.add({TableKey: rollNo, name: name});
}
/**
 * [indexdb_find 数据查询]
 * @param  {[type]} rollNo [主键索引]
 * @return {[type]}        [description]
 */
function indexdb_find(rollNo){
    var request = db.transaction([tablename],"readwrite").objectStore(tablename).get(rollNo);
    request.onsuccess = function(event){
        $("#result").html("Name : "+request.result.name);
         console.log("数据查询成功^_^");
         console.info('Results:'+request.result.name);
    };
}
/**
 * [indexdb_update 更新数据库操作]
 * @param  {[type]} rollNo [主键索引]
 * @param  {[type]} name   [需要更新的值]
 * @return {[type]}        [description]
 */
function indexdb_update(rollNo,name){
    var transaction = db.transaction([tablename],"readwrite");
    var objectStore = transaction.objectStore(tablename);
    var request = objectStore.get(rollNo);
    request.onsuccess = function(event){
        $("#result").html("Updating : "+request.result.name + " to " + name);
        console.info("Updating : "+request.result.name + " => " + name);
        request.result.name = name;
        objectStore.put(request.result);
        console.log("数据更新成功^_^");
    };
}
/**
 * [indexdb_del 删除数据库]
 * @param  {[type]} name [名称]
 * @return {[type]}      [description]
 */
function indexdb_del(name){
	indexedDB.deleteDatabase('testDB');
	console.log(name+'->数据库删除成功^_^');
}